package com.we.wfc.common.redisson;

import com.google.common.collect.Maps;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.util.*;

/**
 * @Description: 请求加盐标记工具类
 * @Author:Liangzy(Feeling)
 * @Date:Create in 2020/1/8 10:28 上午
 */
public class RequestSaltSignUtil {

    public static String requestMd5Sign(WrappedHttpServletRequest request) throws IOException {
        Map<String, String> signMap = Maps.newHashMap();
        String requestParams = request.getRequestParams();
        signMap.put("requestParams", requestParams);
        signMap.put("uri", request.getRequestURI());
        signMap.put("accessTokenValue", request.getAttribute("OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE").toString());
        Enumeration<String> attributeNames = request.getAttributeNames();
        return md5Sign(signMap, "SignKey-we");
    }


    /**
     * 加签
     *
     * @param map
     * @return
     */
    public static String md5Sign(Map<String, String> map, String signKey) {
        if (map == null) {
            return null;
        }
        List<String> keyList = new ArrayList<>(map.keySet());
        Collections.sort(keyList);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            Object value = map.get(key);
            sb.append(key + "=" + value + "&");
        }
        String signStr = sb.substring(0, sb.length() - 1) + signKey;
        String md5Str = DigestUtils.md5Hex(signStr);
        return md5Str;
    }
}
